package com.sjw.workflow.agent;

import com.sjw.workflow.core.WorkflowContext;
// import org.slf4j.Logger;
// import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.stream.Collectors;

/**
 * 报告生成Agent
 * 负责整合前面Agent的结果并生成最终报告
 */
public class ReportGenerationAgent extends BaseAgent {
    
    // private static final Logger logger = LoggerFactory.getLogger(ReportGenerationAgent.class);
    
    public ReportGenerationAgent() {
        super("report-generator", "Report Generation Agent", 
              "Generates comprehensive reports by integrating results from multiple agents");
    }
    
    @Override
    protected Map<String, Object> executeInternal(Map<String, Object> input, WorkflowContext context) throws Exception {
        System.out.println("ReportGenerationAgent starting report generation");
        
        Map<String, Object> output = new HashMap<>();
        
        // 收集所有Agent的结果
        Map<String, Object> allResults = collectAgentResults(context);
        
        // 生成综合报告
        Map<String, Object> report = generateComprehensiveReport(allResults, context);
        
        // 准备输出
        output.put("report", report);
        output.put("summary", generateSummary(allResults));
        output.put("metadata", generateMetadata(context));
        output.put("generationTime", System.currentTimeMillis());
        output.put("status", "success");
        
        // 模拟一些处理时间
        Thread.sleep(1200);
        
        System.out.println("ReportGenerationAgent completed report generation");
        return output;
    }
    
    /**
     * 收集所有Agent的结果
     */
    private Map<String, Object> collectAgentResults(WorkflowContext context) {
        Map<String, Object> results = new HashMap<>();
        
        // 获取数据处理Agent的结果
        Map<String, Object> dataProcessingResult = getAgentResult(context, "data-processor");
        if (!dataProcessingResult.isEmpty()) {
            results.put("dataProcessing", dataProcessingResult);
        }
        
        // 获取验证Agent的结果
        Map<String, Object> validationResult = getAgentResult(context, "validator");
        if (!validationResult.isEmpty()) {
            results.put("validation", validationResult);
        }
        
        // 获取其他可能的结果
        Map<String, com.sjw.workflow.core.AgentResult> allAgentResults = context.getAllAgentResults();
        for (Map.Entry<String, com.sjw.workflow.core.AgentResult> entry : allAgentResults.entrySet()) {
            String agentId = entry.getKey();
            if (!agentId.equals("data-processor") && !agentId.equals("validator")) {
                results.put(agentId, entry.getValue().getOutput());
            }
        }
        
        return results;
    }
    
    /**
     * 生成综合报告
     */
    private Map<String, Object> generateComprehensiveReport(Map<String, Object> allResults, WorkflowContext context) {
        Map<String, Object> report = new HashMap<>();
        
        // 报告头部信息
        report.put("title", "Workflow Execution Report");
        report.put("workflowId", context.getWorkflowId());
        report.put("generatedAt", System.currentTimeMillis());
        report.put("executionTime", context.getExecutionTime());
        
        // 执行摘要
        report.put("executiveSummary", generateExecutiveSummary(allResults, context));
        
        // 详细结果
        report.put("detailedResults", allResults);
        
        // 性能指标
        report.put("performanceMetrics", generatePerformanceMetrics(context));
        
        // 建议和结论
        report.put("conclusions", generateConclusions(allResults));
        report.put("recommendations", generateRecommendations(allResults));
        
        return report;
    }
    
    /**
     * 生成执行摘要
     */
    private Map<String, Object> generateExecutiveSummary(Map<String, Object> allResults, WorkflowContext context) {
        Map<String, Object> summary = new HashMap<>();
        
        int totalAgents = context.getAllAgentResults().size();
        long successfulAgents = context.getAllAgentResults().values().stream()
                .filter(result -> result.getStatus() == com.sjw.workflow.core.ExecutionStatus.SUCCESS)
                .count();
        
        summary.put("totalAgents", totalAgents);
        summary.put("successfulAgents", successfulAgents);
        summary.put("successRate", totalAgents > 0 ? (double) successfulAgents / totalAgents : 0.0);
        summary.put("overallStatus", successfulAgents == totalAgents ? "SUCCESS" : "PARTIAL_SUCCESS");
        summary.put("executionTime", context.getExecutionTime());
        
        return summary;
    }
    
    /**
     * 生成性能指标
     */
    private Map<String, Object> generatePerformanceMetrics(WorkflowContext context) {
        Map<String, Object> metrics = new HashMap<>();
        
        Map<String, com.sjw.workflow.core.AgentResult> allResults = context.getAllAgentResults();
        
        if (!allResults.isEmpty()) {
            long totalExecutionTime = allResults.values().stream()
                    .mapToLong(com.sjw.workflow.core.AgentResult::getExecutionTime)
                    .sum();
            
            long avgExecutionTime = totalExecutionTime / allResults.size();
            
            long maxExecutionTime = allResults.values().stream()
                    .mapToLong(com.sjw.workflow.core.AgentResult::getExecutionTime)
                    .max()
                    .orElse(0);
            
            long minExecutionTime = allResults.values().stream()
                    .mapToLong(com.sjw.workflow.core.AgentResult::getExecutionTime)
                    .min()
                    .orElse(0);
            
            metrics.put("totalExecutionTime", totalExecutionTime);
            metrics.put("averageExecutionTime", avgExecutionTime);
            metrics.put("maxExecutionTime", maxExecutionTime);
            metrics.put("minExecutionTime", minExecutionTime);
            metrics.put("workflowOverhead", context.getExecutionTime() - totalExecutionTime);
        }
        
        return metrics;
    }
    
    /**
     * 生成结论
     */
    private List<String> generateConclusions(Map<String, Object> allResults) {
        List<String> conclusions = new ArrayList<>();
        
        if (allResults.containsKey("dataProcessing")) {
            conclusions.add("Data processing completed successfully");
        }
        
        if (allResults.containsKey("validation")) {
            Map<String, Object> validation = (Map<String, Object>) allResults.get("validation");
            Boolean isValid = (Boolean) validation.get("isValid");
            if (Boolean.TRUE.equals(isValid)) {
                conclusions.add("Data validation passed all checks");
            } else {
                conclusions.add("Data validation failed - review errors before proceeding");
            }
        }
        
        conclusions.add("Workflow execution completed with comprehensive analysis");
        
        return conclusions;
    }
    
    /**
     * 生成建议
     */
    private List<String> generateRecommendations(Map<String, Object> allResults) {
        List<String> recommendations = new ArrayList<>();
        
        if (allResults.containsKey("validation")) {
            Map<String, Object> validation = (Map<String, Object>) allResults.get("validation");
            List<String> warnings = (List<String>) validation.get("warnings");
            
            if (warnings != null && !warnings.isEmpty()) {
                recommendations.add("Address validation warnings to improve data quality");
            }
        }
        
        recommendations.add("Consider implementing additional data quality checks");
        recommendations.add("Monitor workflow performance for optimization opportunities");
        
        return recommendations;
    }
    
    /**
     * 生成摘要
     */
    private Map<String, Object> generateSummary(Map<String, Object> allResults) {
        Map<String, Object> summary = new HashMap<>();
        
        summary.put("totalResults", allResults.size());
        summary.put("hasDataProcessing", allResults.containsKey("dataProcessing"));
        summary.put("hasValidation", allResults.containsKey("validation"));
        summary.put("allSuccessful", allResults.values().stream()
                .allMatch(result -> result instanceof Map && 
                        Boolean.TRUE.equals(((Map<String, Object>) result).get("status"))));
        
        return summary;
    }
    
    /**
     * 生成元数据
     */
    private Map<String, Object> generateMetadata(WorkflowContext context) {
        Map<String, Object> metadata = new HashMap<>();
        
        metadata.put("workflowId", context.getWorkflowId());
        metadata.put("executionLog", context.getExecutionLog());
        metadata.put("globalData", context.getAllGlobalData());
        
        return metadata;
    }
}
